<?php
/**
 * Created by PhpStorm.
 * User: yuanluke
 * Date: 3/14/17
 * Time: 23:53
 */

namespace App\Http\Utils\ControllerTrait;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Log;
use App\Http\Utils\Common\OperResult;

trait WechatQrCodeTrait {

    public function createWxaQrCode(Request $request) {
        try {
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $token = $this->getToken();
            if(empty($token)){
                return 'access_token missing';
            }
            $content = $this->createCode($token,$request->input('pages',''));
            file_put_contents(public_path('assets/qrcode/'.time().'.jpg'), $content);// 写入文件
            return $content;
        } catch (ErrorException $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            return 'fail';
        }
    }

    public function getToken()
    {
        $tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxedf294ed867d3f2f&secret=29725906c00b5e3054d0c9cb89cf1599';
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', $tokenUrl);
        $json = \GuzzleHttp\json_decode($response->getBody());
        $token = empty($json->access_token) ? null : $json->access_token;
        Log::info($token);
        return $token;
    }

    public function createCode($token,$pages)
    {
        $client = new \GuzzleHttp\Client();
        $url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$token;
        $body['path'] = 'pages/register/register';
        $body['width'] = 430;
        if(empty($pages)){
            $pages = 'pages/register/register';
        }
//        $response = $client->post($url, [ 'body' => json_encode($body)]);
        $response = $client->request('POST', $url,
            array(
                'headers' => array('Content-Type'=>'application/json'),
                'json' => [
                    'path' => $pages,
                    'width' => 430,
                ]
            )
        );
        return $response->getBody();
    }


}